#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/wait.h>


typedef int (*process)(void *arg);

pid_t create_process(process entry, void *arg)
{
	int exit_value;
	pid_t pid;
	
	if(!entry)
		return -1;
	
	//创建子进程
	pid = fork();
	if(pid == 0)
	{
		//fork在子进程中返回0
		exit_value = entry(arg);
		exit(exit_value);
	}
	//fork在父进程中返回子进程的ID
	return pid;
}

int process1(void *arg)
{
	int i;
	int max_fd;
	int fd;
	
	//创建新会话，脱离终端
	setsid();
	//改变当前工作目录
	chdir("./");
	//设置权限掩码
	umask(0);
	//关闭不需要的文件
	max_fd=getdtablesize();
	for(i=0; i<=max_fd; i++)
	{
		if(i == 1)
		{
			//从定向stdout
			fd = open("./terminal.txt", O_CREAT|O_RDWR|O_APPEND, 0777);
			if(fd == -1)
				return -1;
			if(dup2(fd, i) == -1)
				return -1;
			close(fd);
		}
		else
			close(i);
	}
	
	//执行守护进程任务
	printf("daemon test\r\n");
	
	return 0;
}

int main(int argv, char *argc[])
{
	pid_t pid1;
	
	//创建子进程
	pid1 = create_process(process1, "process1;\r\n");
	printf("process1 PID=%d\r\n", pid1);

	//父进程退出
	return 0;
}